import axios from 'axios'


const service = axios.create({
    responseType: 'arraybuffer',
})
service.interceptors.request.use(config => {
    config.headers['Authorization'] = window.localStorage.getItem('token')
    return config
}, error => {
    console.log(error)
})
service.interceptors.response.use(res => {
    const headers = res.headers;
    //正则表达式,虽然可以接流,但是毕竟是axios,json也可以返回,需要判断一下
    let reg = RegExp(/application\/json/);
    if (headers['content-type'].match(reg)) {
        res.data = uintToString(res.data)
    } else {
        let fileDownload = require('js-file-download')
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]
        let contentType = headers['content-type']
        fileName = decodeURIComponent(fileName)
        fileDownload(res.data, fileName, contentType)
    }
}, error => {
    console.log(error)
})


function uintToString(uintArray) {
    let encodedString = String.fromCharCode.apply(null, new Uint8Array(uintArray))
    let decodedString = decodeURIComponent(encodeURIComponent(encodedString))
    return JSON.parse(decodedString)
}

let base = ''
export const downloadRequest = (url, data) => {
    return service({
        method: 'GET',
        url: `${base}${url}`,
        data: data
    })
}
export default service;
